<%@ page language="java" session="true" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<jsp:include page="../common/framework/header.jsp" />
<style>
	body{
		font-size:12px;color:#333;font-family:微软雅黑;background-color: #fff;
	}
  .form-inline .form-control {
    width: 100%;
	}
	.checkbox input[type=checkbox], .checkbox-inline input[type=checkbox], .radio input[type=radio], .radio-inline input[type=radio] {
    margin-top: 2px;
}
.checkbox, .radio {
    margin-top: 5px;
}
</style>

	<div class="container-fluid" style="padding-right:50px;padding-left:0;">
    <form id ="moduleForm">
        <div class = "form-inline row" style = "margin-top : 20px;">
            <div class = "form-group col-sm-12 col-xs-12">
                <label class="col-sm-2 col-xs-2" style="padding:6px 0 0 0;text-align:right;"><font color=red>*</font>模块名称：</label>
		        <div class="col-sm-10 col-xs-10" style="padding-right:0;">
		        	<input type = "text" class="  form-control" id="moduleNm" name = "moduleNm" >
            	 </div>
            </div>
        </div>

        <div class = "form-inline row" style = "margin-top : 10px;">
            <div class = "form-group col-sm-12 col-xs-12">
                <label class="col-xs-2" style="padding:6px 0 0 0;text-align:right;">测试机：</label>
                <div class="col-xs-10" style="padding-right:0;">
		        	 <select class="form-control" style="width:100%;" id="testResource" name="testResource">
						<option value="0">直连</option>
					</select>
		        </div>
            </div>
        </div>

        <div class = "form-inline row" >
	        <div class = "form-group col-sm-12 col-xs-12">
	            <div class = "col-sm-10 checkbox" style="margin-left:130px;">
	                    <input id="applyToIntfc" type="checkbox">&nbsp;&nbsp;&nbsp;测试机应用于模块下所有接口
	            </div>
	        </div>
        </div>
    </form>
    <div class="form-inline row">
        <div class = "form-group col-sm-12 col-xs-12"  >
			<table class="table table-hover" style="word-break:break-all; word-wrap:break-all;margin-left: 30px;">
				<thead>
					<tr>
						<th class="col-md-5">变量名</th>
						<th class="col-md-5">变量值</th>
						<th class="col-md-1">
							<a id="addVar" class="btn btn-xs btn-primary ">
								<span class="glyphicon glyphicon-plus"></span>
							</a>
						</th>
					</tr>
				</thead>
				<tbody id="varList"></tbody>
			</table>
			</div>
		</div>
</div>
	<jsp:include page="../common/framework/script.jsp" />
    <script type="text/javascript">
    var flag = parent.flag;

    //确定按钮，提交表单
    var submit = function(){
  	  $('#moduleForm').valid(function () {
  		var varArr = checkVar($("#varList").children());
		if (!varArr){
			return;
		}
  			$.ajax({
  				type : 'POST',
  				async : true,//异步
  				traditional: true,
  				data : {
  					"moduleId" : (flag != -1) ? parent.$("#moduleTable").grid("getRow", flag).moduleId : '',
  					"moduleNm" : $("#moduleNm").val(),
  					//"moduleCode" : $("#moduleCode").val(),
  					//"projectId" : $("#projectId").val(),
  					"resourceId" : $("#testResource").val(),
  					"applyToIntfc" : $("#applyToIntfc").is(':checked') ? "Y" : "N",
  					"flag" : flag,
  					"varJson":JSON.stringify(varArr),//编辑变量
  				},
  				url: "../module/saveOrUpdateModule",
  		        dataType : "json",
  		        contentType:"application/x-www-form-urlencoded;charset=utf-8",
  				success: function(data){
  					    if(data == 101){
  							parent.parent.layer.msg('请登录', {
  								icon : 2,
  								time : 2000
  								});
  						}else if(data==1){
  							parent.layer.msg('保存成功', {icon: 1});
  							//刷新grid
  					    	parent.loadFlag = 0;
  						}else if(data==0){
  							parent.parent.layer.msg('数据库操作失败！', {
  								icon : 2,
  								time : 2000
  								});
  						}
  						else if(data==4){
  							parent.parent.layer.msg('模块重复！', {
  								icon : 2,
  								time : 2000
  								});
  						}
  						setTimeout(function(){
  							parent.layer.closeAll();
  							}, 500);
  				},
  				error : function(){
  					layer.msg('保存失败',{
  						icon : 2,
  						time : 2000
  					});
  				}
  			});
  		});

    };



    var closeLayer = function(){
    	//取消不刷新grid
    	parent.loadFlag =1;
    	parent.layer.closeAll();
    };


//     $("#testResource").ready(function(){
//     	$.ajax({
//     		type : 'POST',
//     		async : false,
//     		url : '../resource/listTestResource',
//     		data:{"resourceType":6},
//     		dataType: "json",
//     		success : function(res){
//     			$.each(res,function(i,item){
//     				$("#testResource").append("<option value='"+ item.resourceId+"'>" + item.resourceName+"</option>");
//     			});
//     	 		if (undefined != parent.layer.moduleId && 0 < parent.layer.moduleId.length){
//     			    loadModule();
//     	 		}
//     		},
//     		error : function(responseObject){
//     			var headerStaus = responseObject.status;
//     			if(headerStatus == 400){
//     				var errorText = responseObject.responseText;
//     				var errorObject = eval("("+errorText+")");
//     			}
//     		}
//     	});
//     });

    function loadModule(){
    	$.ajax({
			type:"POST",
			data:{"moduleId":parent.layer.moduleId},
			dataType:"json",
			url:"../module/getModule",
			scriptCharset: 'utf-8',
			success:function(result){
				$("#moduleNm").val(result.moduleNm);
				//$("#moduleCode").val(result.moduleCode);
				$("#projectId").val(result.projectId);
				$("#testResource").val(result.resourceId);
				$("#applyToIntfc").attr("checked","Y" == result.applyToIntfc);
			}
		});
    }

    $("input").keypress(function(e){
		var keycode = (e.keyCode ? e.keyCode : e.which);
		if (13 == keycode) {
			submit();
		}
	});


    /* 编辑变量相关 */
// 	$(function(){
// 		var moduleId = (flag != -1) ? parent.$("#moduleTable").grid("getRow", flag).moduleId : '';
// 		loadVar(moduleId);
// 	});

/* 	function getParam(){
		return {
			"moduleId" : request().moduleId
			};
	}; */

// 	function loadVar(moduleId){
// 		$.ajax({
// 			type:"POST",
// 			data:{"moduleId":moduleId},
// 			dataType:"json",
// 			url:"../module/listModuleVar",
// 			scriptCharset: 'utf-8',
// 			success:function(result){
// 				var varList = $('#varList');
// 				varList.empty();
// 				$.each(result,function(i,item){
// 					addVar(varList,item);
// 				});
// 			}
// 		});
// 	}

	 function creadtVarRow(item){
			var tr = $("<tr class='tr-task'></tr>");
			var tdVarNm = $("<td><a href='#'  name='varNm' data-type='text' data-pk='1' data-title='变量名' data-placement='right'>"+item.varNm+"</a></td>");
			var tdVarValue = $("<td><a href='#' name='varValue' data-type='text' data-pk='1' data-title='变量值' data-placement='right'>"+item.varValue+"</a></td>");
			var tdBtn = $("<td></td>");
			var del = $("<i class='fa fa-trash trash-lg' ></i>");
			del.attr("onclick", "delVar(this)");
			var tdBtn = $("<td></td>");
			tdBtn.append(del);
			tr.append(tdVarNm).append(tdVarValue).append(tdBtn);
			tr.attr("varId", item.varId);
			return tr;
		}

	 function editableRow(tr,item){
			tr.find("a[name='varNm']").editable('option', 'validate', function(v) {
			    if (2048 < v.length){
			    	return "操作url不能超过2048个字符";
			    }
			});
			tr.find("a[name='varValue']").editable('option', 'validate', function(v) {
			    if (512 < v.length){
			    	return "节点不能超过512个字符";
			    }
			});
		}

	 function addVar(varList,item){
			var tr = creadtVarRow(item);
			varList.append(tr);
			editableRow(tr,item);
		}

	 function delVar(button) {
			var row = $(button).parent().parent();
			$(row).remove();
		}

	 var tempVarId = 0;

	 function initVar(){
		 tempVarId++;
			var variable = new Object();
			variable.varId = "temp"+tempVarId;
			variable.varNm = "";
			variable.varValue = "";
			return variable;
		}

	 $('#addVar').click(function() {
		 addVar($('#varList'),initVar());
		});

	 //提交时判断变量
		function checkVar(vars){
			var varArr = [];
			var duplicateArr = [];
			var length = vars.length;
			for (var i = 0; i < length; i++) {
				var varRow = $(vars[i]);
				var varNm = $(varRow.find("td a[name='varNm']:first")).editable('getValue', true);
				if (undefined == varNm || 1 > varNm.length){
					layer.msg("变量名不能为空", {icon: 2});
					setTimeout(function(){
						  layer.closeAll();
						}, 1000);
					return false;
				}
				if (50 < varNm.length){
					layer.msg("变量名过长，过长值为：" + varNm, {icon: 2});
					setTimeout(function(){
						  layer.closeAll();
						}, 1000);
					return false;
				}
				if (-1 != duplicateArr.indexOf(varNm)){
					layer.msg("变量名重复，重复值为：" + varNm, {icon: 2});
					setTimeout(function(){
						  layer.closeAll();
						}, 1000);
					return false;
				}
				duplicateArr.push(varNm);
				var varValue = $(varRow.find("td a[name='varValue']:first")).editable('getValue', true);
				if (undefined == varValue || 1 > varValue.length){
					layer.msg("变量值不能为空", {icon: 2});
					setTimeout(function(){
						  layer.closeAll();
						}, 1000);
					return false;
				}
				if (100 < varValue.length){
					layer.msg("变量值过长，过长值为：" + varValue, {icon: 2});
					setTimeout(function(){
						  layer.closeAll();
						}, 1000);
					return false;
				}
				var variable = new Object();
				variable.varId = varRow.attr("varId");
				variable.moduleId =(flag != -1) ? parent.$("#moduleTable").grid("getRow", flag).moduleId : '';
				variable.varNm = varNm;
				variable.varValue = varValue;
				variable.dispOrder = i+1;
				varArr.push(variable);
			}
			return varArr;
		}
   /* 编辑变量相关结束  */
    </script>
<jsp:include page="../common/framework/footer.jsp" />